﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BotonJXC.BLL;
using BotonJXC.Entity;
using BotonJXC.Util;

namespace BotonJXC.Forms
{
    public partial class OutStockForm : BaseMdiForm
    {
        public OutStockForm()
        {
            InitializeComponent();
        }
        public static string[] type;
        private Int32 pageSize = 1;
        private Int32 totalSize;
        OutStocksBLL OutStocksBLL = null;
        OutStocks OutStocks = null;
        ProductBLL  ProductBLL = null;
        WarehouseBLL WarehouseBLL = null;
        private void OutStockForm_Load(object sender, EventArgs e)
        {
 
            this.InitDepartment();
            this.InitStore();
            this.InitWarehouse();
            this.InitAccumeModes();
            InitForm();
            LoadDate();
        }

        private void LoadDate() {
 
   
           //封装查询条件
            OutStocks OutStocks = new OutStocks();
            OutStocks.CreatePlace =type[0];
            OutStocks.OutType = type[1];

            if (OutStocksBLL == null) OutStocksBLL = new OutStocksBLL();
            PageModel<OutStocks> pageModel = OutStocksBLL.findOutStocksByCondition( OutStocks, (pageSize - 1) * 1, 1);
            if (pageModel.Results.Count == 0)
            {
                this.deletedBtn.Enabled = false;
                this.auditBtn.Enabled = false;
                this.saveBtn.Enabled = false;
            }
            else
            {
               
                //赋值
                foreach (OutStocks newOutStocks in pageModel.Results)
                {
                    this.OutStocks = newOutStocks;
                }
                //已审核
                if (Utils.ToString((Int32)Status.AuditPass).Equals(this.OutStocks.AuditStatus))
                { 
                    this.deletedBtn.Enabled = false;
                    this.auditBtn.Enabled = false;
                    this.saveBtn.Enabled = false;
                }
                else {
                    this.deletedBtn.Enabled = true;
                    this.auditBtn.Enabled = true;
                    this.saveBtn.Enabled = true;
                }

                //分页
                pageBtnControl(pageModel);

                //初始数据
                this.outSnText.Text = this.OutStocks.OutSn;
                this.SalesmanLabel.Text = "业务员: " + this.OutStocks.Salesman;
                this.MgDepartmentCboBox.Text = this.OutStocks.MgDepartment == null ? "" : this.OutStocks.MgDepartment.DepName;
                this.FinDepartmentCboBox.Text = this.OutStocks.FinDepartment == null ? "" : this.OutStocks.FinDepartment.DepName;

                this.InStoreCboBox.Text = this.OutStocks.InStore == null ? "" : this.OutStocks.InStore.StoreName;
                this.InWarehouseCbobox.Text = this.OutStocks.InWarehouse == null ? "" : this.OutStocks.InWarehouse.Name;
                this.OutStoreCboBox1.Text = this.OutStocks.OutStore == null ? "" : this.OutStocks.OutStore.StoreName;
                this.EffDayText.Text = this.OutStocks.EffDay == null ? "" : this.OutStocks.EffDay.ToString();
                if (this.OutStocks.GenPicking == "Y")
                {
                    this.pickCheckBox.Checked = true;
                }
                else {
                    this.pickCheckBox.Checked = false;
                }
                if (this.OutStocks.Orders != null)
                {
                    InStoreCboBox.Enabled = false;
                    InWarehouseCbobox.Enabled = false;
                    this.OrdersSnLabel.Text = "相关单号: " + this.OutStocks.Orders.OrderSn;
                    this.OrdersTypeLabel.Text = "相关单据类型: " + StatusUtil.getOrdersTypeString(Int32.Parse(this.OutStocks.Orders.OrderType));
                }
                else {
                    InStoreCboBox.Enabled = true;
                    InWarehouseCbobox.Enabled = true;
                }
                this.OrdersStatusLabel.Text = "单据状态: " + StatusUtil.getAuditString(Int32.Parse(this.OutStocks.AuditStatus == null ? "1" : this.OutStocks.AuditStatus));
                if (this.OutStocks.Account != null)
                {
                    this.AccountLabel2.Text = "制单人: " + this.OutStocks.Account.Username;
                    this.AccountLabel1.Text = "制单人: " + this.OutStocks.Account.Username;
                }
                this.CreateTimeLabel2.Text = "制单日期: " + string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.OutStocks.CreateTime);
                this.CreateTimeLabel1.Text = "制单日期: " + string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.OutStocks.CreateTime); 
                if(this.OutStocks.OutAuditAccount !=null)
                this.OutAuditAccountLabel.Text = "配送审核人: " +   this.OutStocks.OutAuditAccount.Username;
                this.OutAuditTimeLabel.Text = "配送审核日期: " + string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.OutStocks.OutAuditTime);
                if (this.OutStocks.InAuditAccount !=null)
                this.InAuditAccountLabel.Text = "入库审核人:　" +  this.OutStocks.InAuditAccount.Username;
                this.InAuditTimeLabel.Text = "入库审核日期: " + string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.OutStocks.InAuditTime); 
                this.PrintTimeLabel1.Text = "打印次数:　" + this.OutStocks.PrintTime;
                this.RemarkText.Text = this.OutStocks.Remark;
                this.outStoreCboBox.Text = this.OutStocks.OutStore == null ? "" : this.OutStocks.OutStore.StoreName;
                this.OutWarehouseCbobox2.Text = this.OutStocks.OutWarehouse == null ? "" : this.OutStocks.OutWarehouse.Name;

                this.OutWarehouseCbobox1.Text = this.OutStocks.OutWarehouse == null ? "" : this.OutStocks.OutWarehouse.Name;
                this.OutWarehouseCbobox2.Text = this.OutStocks.OutWarehouse == null ? "" : this.OutStocks.OutWarehouse.Name;
          
               
                if (this.OutStocks.AuditAccount!=null)
                    this.AuditAccountLabel.Text = "审核人:　" +this.OutStocks.AuditAccount.Username;
                this.AuditTimeLabel.Text = "审核日期: " + string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.OutStocks.AuditTime);
                this.BsCauseText.Text = this.OutStocks.BsCause;
                this.BearModelCboBox.Text = this.OutStocks.AssumeMode == null ? "" : this.OutStocks.AssumeMode.AssumeModeName;


                //初始化datagridView
                    //清空dateGridView
               ProductsDataGridViewOrders.Rows.Clear();
               Double totalRealOutQuantity = 0;//实际配出数，报损数量
               //进价金额
               Double totalDefPurPrice = 0;
                //计划配送数量
               Double totalPlanQuantity = 0;
                //实际配入数量
               Double totalRealInQuantity = 0;
               foreach (OutStocksProducts OutStocksProducts in this.OutStocks.ProductsList)
               {
                   int index = this.ProductsDataGridViewOrders.Rows.Add();
                   this.ProductsDataGridViewOrders.Rows[index].Cells["ProductId"].Value = OutStocksProducts.Product.ProductId;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["ProductCode"].Value = OutStocksProducts.Product.ProductCode;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["Barcode"].Value = OutStocksProducts.Product.Barcode;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["ProductName"].Value = OutStocksProducts.Product.ProductName;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["Unit"].Value = OutStocksProducts.Product.Unit == null ? "" : OutStocksProducts.Product.Unit.UnitName;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["PackSpec"].Value = OutStocksProducts.Product.ProductSpec;

                   this.ProductsDataGridViewOrders.Rows[index].Cells["PlanQuantity"].Value = OutStocksProducts.PlanQuantity; //计划配出数量
                   this.ProductsDataGridViewOrders.Rows[index].Cells["RealOutQuantity"].Value = OutStocksProducts.RealOutQuantity;//实际配出数量
                   this.ProductsDataGridViewOrders.Rows[index].Cells["RealInQuantity"].Value = OutStocksProducts.RealInQuantity;//实际配人数量
                   this.ProductsDataGridViewOrders.Rows[index].Cells["DefPurPrice"].Value = OutStocksProducts.Product.DefPurPrice;//默认进价
                   this.ProductsDataGridViewOrders.Rows[index].Cells["RealOutQuantitys"].Value = OutStocksProducts.RealOutQuantity;//报损数量

                   ProductsDataGridViewOrders["inPurPrice", index].Value =
                         OutStocksProducts.Product.PurPrice * (1 + OutStocksProducts.Product.TaxRate);//含税进价 = 未税进价*(1+税率)
                   ProductsDataGridViewOrders["DefPurPrice", index].Value = OutStocksProducts.Product.DefPurPrice;//默认进价
                   ProductsDataGridViewOrders["TaxRate", index].Value = OutStocksProducts.Product.TaxRate;//税率
                   //计算总数
                   totalRealOutQuantity += OutStocksProducts.RealOutQuantity;
                   totalDefPurPrice += OutStocksProducts.Product.DefPurPrice;
                   totalPlanQuantity += OutStocksProducts.PlanQuantity;
                   totalRealInQuantity += OutStocksProducts.RealInQuantity;
               }
                //总数计算

               InmoneyLabel.Text = "进价金额: " + totalDefPurPrice;
               batNumLabel.Text = "报损数量: " + totalRealOutQuantity;
               InsendNumTrueLabel.Text = "实际配人数量: " + totalRealInQuantity;//实际配人总数
               sendNumLabel.Text = "计划配出数量: " + totalPlanQuantity;
               OutsendNumTrueLabel.Text = "实际配出数量: " + totalRealOutQuantity;

            }    
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageModel"></param>
        private void pageBtnControl(PageModel<OutStocks> pageModel)
        {
            this.totalSize = pageModel.PageCount;

            if (pageSize == totalSize)
            {
                this.next.Enabled = false;
            }
            else
            {
                this.next.Enabled = true;
            }
            if (pageSize == 1)
            {
                this.up.Enabled = false;
            }
            else
            {
                this.up.Enabled = true;
            }
        }

        /// <summary>
        /// 初始化Form
        /// </summary>
        private void InitForm() {
            type = this.Tag.ToString().Split(',');
            if ("1".Equals(type[1]))
            {
                //所有配送出库

                if (!"1".Equals(type[0]))
                {
                    pickCheckBox.Visible = true;
                }
                else {
                    pickCheckBox.Visible = false;
                }
            }
            else if ("2".Equals(type[1]))
            {
                //所有报损

                badPanel.Visible = true;
                InmoneyLabel.Visible = true;//进价金额
                batNumLabel.Visible = true;//报损数量

                sendNumLabel.Visible = false;//计划配送数量
                OutsendNumTrueLabel.Visible = false;//实际配出数量
                InsendNumTrueLabel.Visible = false;//实际配入数量

               // 显示 默认进价，报损数量，税率，含税进价。
                ProductsDataGridViewOrders.Columns["DefPurPrice"].Visible = true;
                ProductsDataGridViewOrders.Columns["RealOutQuantitys"].Visible = true;
                ProductsDataGridViewOrders.Columns["TaxRate"].Visible = true;
                ProductsDataGridViewOrders.Columns["inPurPrice"].Visible = true;

               //隐藏 计划配送数量，配出数量，配入数量，配送入库价，配送入库金额，配出件数，配入件数。
                ProductsDataGridViewOrders.Columns["PlanQuantity"].Visible = false;
                ProductsDataGridViewOrders.Columns["RealOutQuantity"].Visible = false;
                ProductsDataGridViewOrders.Columns["RealInQuantity"].Visible = false;
                ProductsDataGridViewOrders.Columns["InMoney"].Visible = false;
                ProductsDataGridViewOrders.Columns["totalInMoney"].Visible = false;
                ProductsDataGridViewOrders.Columns["RealOutQuantityPack"].Visible = false;
                ProductsDataGridViewOrders.Columns["RealInQuantityPack"].Visible = false;
            }
        
        }
        /// <summary>
        /// 表单还原
        /// </summary>
        private void returnInit() {
            this.outSnText.Text = "";
            this.SalesmanLabel.Text = "业务员: ";
            
            this.EffDayText.Text = "";
            this.pickCheckBox.Checked = false;

            this.OrdersSnLabel.Text = "相关单号: ";
            this.OrdersTypeLabel.Text = "相关单据类型: ";
          
            this.OrdersStatusLabel.Text = "单据状态: ";
            this.AccountLabel2.Text = "制单人: ";
            this.AccountLabel1.Text = "制单人: ";
            this.CreateTimeLabel2.Text = "制单日期: " ;
            this.CreateTimeLabel1.Text = "制单日期: " ;
            this.OutAuditAccountLabel.Text = "配送审核人: " ;
            this.OutAuditTimeLabel.Text = "配送审核日期: " ;
            this.InAuditAccountLabel.Text = "入库审核人:　" ;
            this.InAuditTimeLabel.Text = "入库审核日期: ";
            this.PrintTimeLabel1.Text = "打印次数:　" ;
            this.RemarkText.Text = "";
            this.AuditAccountLabel.Text = "审核人:　";
            this.AuditTimeLabel.Text = "审核日期: " ;
            this.BsCauseText.Text = "";
            InmoneyLabel.Text = "进价金额: " ;
            batNumLabel.Text = "报损数量: " ;
            InsendNumTrueLabel.Text = "实际配人数量: ";
            sendNumLabel.Text = "计划配出数量: ";
            OutsendNumTrueLabel.Text = "实际配出数量: " ;
            //this.BearModelCboBox.Text = "";
            //this.outStoreCboBox.Text = "";
            //this.OutWarehouseCbobox2.Text = "";
            //this.OutWarehouseCbobox1.Text = "";
            //this.OutWarehouseCbobox2.Text = "";
            //this.InWarehouseCbobox.Text = "";
            //this.MgDepartmentCboBox.Text = "";
            //this.FinDepartmentCboBox.Text = "";
            //this.InStoreCboBox.Text = "";
            //this.OutStoreCboBox1.Text = "";

            this.BearModelCboBox.SelectedIndex = 0;//选中第一项
            this.outStoreCboBox.SelectedIndex = 0;//选中第一项
            this.OutWarehouseCbobox2.SelectedIndex = 0;//选中第一项
            this.OutWarehouseCbobox1.SelectedIndex = 0;//选中第一项
            this.OutWarehouseCbobox2.SelectedIndex = 0;//选中第一项
            this.InWarehouseCbobox.SelectedIndex = 0;//选中第一项
            this.MgDepartmentCboBox.SelectedIndex = 0;//选中第一项
            this.FinDepartmentCboBox.SelectedIndex = 0;//选中第一项
            this.InStoreCboBox.SelectedIndex = 0;//选中第一项
            this.OutStoreCboBox1.SelectedIndex = 0;//选中第一项
        }
        /// <summary>
        /// 点新建表单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addBtn_Click(object sender, EventArgs e)
        {
            this.saveBtn.Tag = "add";
            this.deletedBtn.Enabled = false;
            this.saveBtn.Enabled = true;
            ProductsDataGridViewOrders.Rows.Clear();
            returnInit();
        }


        /// <summary>
        /// 获取出库单
        /// </summary>
        /// <param name="Orders"></param>
        /// <returns></returns>
        private OutStocks GetOutStocks( )
        {

            OutStocks OutStocks = null;

            if ("add".Equals(this.saveBtn.Tag))
            {
                OutStocks = new OutStocks();
               
                if ("1".Equals(type[0]))
                {
                    OutStocks.OutSn = new BillSNGenerator().GeneratorBillSn(BillType.OutStock, BillSource.Store, LoginForm.StoreId);
                }
                else if ("2".Equals(type[0]))
                {
                    OutStocks.OutSn = new BillSNGenerator().GeneratorBillSn(BillType.OutStock, BillSource.DistributionCenter, LoginForm.StoreId);
                }
                else if ("4".Equals(type[0]))
                {
                    OutStocks.OutSn = new BillSNGenerator().GeneratorBillSn(BillType.OutStock, BillSource.Process, LoginForm.StoreId);
                }
                //出库地
                //OutStocks.OutWarehouse = Orders.Warehouse;
                OutStocks.Account = LoginForm.Account;
                OutStocks.CreateTime = DateTime.Now;

                OutStocks.OrgDepId = LoginForm.DepId;
                OutStocks.OrgId = LoginForm.StoreId;
                OutStocks.AuditStatus = "1";

                OutStocks.CreatePlace = type[0];
                OutStocks.OutType = type[1];
                //业务员
                OutStocks.Salesman = "";
            }
            else {
                OutStocks = this.OutStocks;
                //业务员
                OutStocks.Salesman = LoginForm.Account.Username;
            }
            if ("1".Equals(type[1]))
            {
                //出库单

                //配出分店
                OutStocks.OutStore = (Store)this.OutStoreCboBox1.SelectedItem;//获取当前选项 this.OutStoreCboBox1
                //配出库存地
                OutStocks.OutWarehouse = (Warehouse)this.OutWarehouseCbobox1.SelectedItem;
            }
            else if ("2".Equals(type[1]))
            {
                //报损单

                //报损分店
                OutStocks.OutStore = (Store)this.outStoreCboBox.SelectedItem;//获取当前选项 this.OutStoreCboBox1
                //库存地
                OutStocks.OutWarehouse = (Warehouse)this.OutWarehouseCbobox2.SelectedItem;
            }
            //配入分店
            OutStocks.InStore = (Store)this.InStoreCboBox.SelectedItem;//获取当前选项 this.OutStoreCboBox1
            //配入库存地
            OutStocks.InWarehouse = (Warehouse)this.InWarehouseCbobox.SelectedItem; 

            
            //备注
            OutStocks.Remark = this.RemarkText.Text;
            //管理部
            OutStocks.MgDepartment = (Department)this.MgDepartmentCboBox.SelectedItem;
            //财务部
            OutStocks.FinDepartment = (Department)this.FinDepartmentCboBox.SelectedItem;

            //报损原因
            OutStocks.BsCause = this.BsCauseText.Text;
            //承担方式
            OutStocks.AssumeMode = (AssumeMode)this.BearModelCboBox.SelectedItem;
            //是否生成拣货单
            OutStocks.GenPicking = this.pickCheckBox.Checked ? "Y" : "N";
            //有效期
            OutStocks.EffDay =Utils.ToInt( this.EffDayText.Text , 0);
            //货品信息           
            OutStocks.ProductsList = GetOutStocksProducts();

            return OutStocks;
        }
        /// <summary>
        /// 获取货品信息
        /// </summary>
        /// <returns></returns>
        public IList<OutStocksProducts> GetOutStocksProducts()
        {
            IList<OutStocksProducts> oplist = new List<OutStocksProducts>();
            for (int i = 0; i < ProductsDataGridViewOrders.Rows.Count - 1; i++)//如果DataGridView中有空的数据，则提示数据输入不完整并退出添加，不包括标题行
            {
                OutStocksProducts OutStocksProducts = new OutStocksProducts();
                Product Product = new Product();
                Product.ProductId = Utils.ToInt(ProductsDataGridViewOrders["ProductId", i].Value, 0);
                OutStocksProducts.Product = Product;

                OutStocksProducts.PlanQuantity = Utils.ToDouble(ProductsDataGridViewOrders["PlanQuantity", i].Value, 0);

                OutStocksProducts.RealOutQuantity = Utils.ToDouble(ProductsDataGridViewOrders["RealOutQuantity", i].Value, 0);
                 if (OutStocksProducts.RealOutQuantity == 0 )
                    OutStocksProducts.RealOutQuantity = Utils.ToDouble(ProductsDataGridViewOrders["RealOutQuantitys", i].Value, 0);

                OutStocksProducts.RealInQuantity = Utils.ToDouble(ProductsDataGridViewOrders["RealInQuantity", i].Value, 0);
                OutStocksProducts.Price = Utils.ToDouble(ProductsDataGridViewOrders["Price", i].Value, 0);
                OutStocksProducts.Amount = OutStocksProducts.Price * OutStocksProducts.RealOutQuantity;
                OutStocksProducts.TaxRate = Utils.ToDouble(ProductsDataGridViewOrders["TaxRate", i].Value, 0);
                //OutStocksProducts.AllocateAddRate = Utils.ToDouble(ProductsDataGridViewOrders["AllocateAddRate", i].Value, 0);

                OutStocksProducts.InputSeq = i + 1;
 
                oplist.Add(OutStocksProducts);
            }
            return oplist;
        }
  
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveBtn_Click(object sender, EventArgs e)
        {
            if(this.OutStocksBLL==null) this.OutStocksBLL = new  OutStocksBLL();
          
           if ("add".Equals(this.saveBtn.Tag))
            {
               
              bool result = OutStocksBLL.saveOutStocks(GetOutStocks());
               if (result)
                {
                    MessageBox.Show("单据添加成功!");
                    LoadDate();
                    this.saveBtn.Tag = "up";           
                    this.saveBtn.Enabled = true;
                }
                else
                {
                    MessageBox.Show("单据添加失败!");
                }
            }
           else  if ("up".Equals(this.saveBtn.Tag))
           {
             bool result = OutStocksBLL.updateOutStocks(GetOutStocks());
                if (result)
                {
                    MessageBox.Show("单据修改成功!");
                }
                else
                {
                    MessageBox.Show("单据修改失败!");
                }
            }
        }
        /// <summary>
        /// 删除货品信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteProductBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除该行数据吗？", "删除确认",
               MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 确定 删除
                foreach (DataGridViewRow r in ProductsDataGridViewOrders.SelectedRows)
                {
                    if (!r.IsNewRow)
                    {
                        ProductsDataGridViewOrders.Rows.Remove(r);
                    }
                }
            }
        }

        private void deletedBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除当前出库订单吗？", "删除确认",
            MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            
                if(OutStocksBLL ==null) OutStocksBLL = new OutStocksBLL();
                bool result = OutStocksBLL.DeleteOutStocks(OutStocks);
                if (result)
                {
                    MessageBox.Show("单据删除成功!");
                    LoadDate();
                }
                else
                {
                    MessageBox.Show("单据删除失败!");
                }

            }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void auditBtn_Click(object sender, EventArgs e)
        {
            if (this.OutStocksBLL == null) this.OutStocksBLL = new OutStocksBLL();

            if (OutStocks != null) {
                
                bool result = false;
                OutStocks.AuditAccount = LoginForm.Account;
                OutStocks.AuditStatus = Utils.ToString((Int32)Status.AuditPass); ;
                OutStocks.AuditTime = DateTime.Now;
                if ("2".Equals(OutStocks.OutType))
                {
                    result = OutStocksBLL.updateOutStocks(OutStocks ,true);
                  
                }
                else {

                    OutStocks.OutAuditAccount = LoginForm.Account;
                    OutStocks.OutAuditTime = DateTime.Now;
                    //审核备注

           
                    //是否生成拣货单
                    if ("Y".Equals(OutStocks.GenPicking))
                    {
                        result = OutStocksBLL.updateOutStocks(OutStocks, getInStocks(), getPickings(),true);
                    }
                    else {
                        result = OutStocksBLL.updateOutStocks(OutStocks, getInStocks(), true);
                    }
         
                 }

                if (result)
                {
                    MessageBox.Show("单据审核成功!");
                    LoadDate();
                }
                else
                {
                    MessageBox.Show("单据删除失败!");
                }
            }
           
            
        }
        /// <summary>
        /// 自动生成入库单
        /// </summary>
        private InStocks getInStocks()
        {

            InStocks InStocks = new InStocks();
            InStocks.InStore = OutStocks.InStore;
            InStocks.InWarehouse = OutStocks.InWarehouse;
 
            InStocks.OutStore = OutStocks.OutStore;
            InStocks.OutWarehouse = OutStocks.OutWarehouse;

            InStocks.Account = LoginForm.Account;
            InStocks.CreateTime = DateTime.Now;

            InStocks.AuditStatus = "1";

            InStocks.OutAuditAccount = LoginForm.Account;
            InStocks.OutAuditTime = DateTime.Now;
            InStocks.EffDay = 7;
            InStocks.Remark = "系统自动生成";

            InStocks.OutStocks = OutStocks;
            InStocks.InType = "1";

            InStocks.OrgId = OutStocks.InStore.StoreId;

            InStocks.CreatePlace = OutStocks.InStore.StoreType.ToString();
            if (OutStocks.InStore.StoreType == 1)
            {
                InStocks.InSn = new BillSNGenerator().GeneratorBillSn(BillType.OutStock, BillSource.Store, LoginForm.StoreId);
            }
            else if (OutStocks.InStore.StoreType == 2)
            {
                InStocks.InSn = new BillSNGenerator().GeneratorBillSn(BillType.OutStock, BillSource.DistributionCenter, LoginForm.StoreId);
            }
            else if (OutStocks.InStore.StoreType == 4)
            {
                InStocks.InSn = new BillSNGenerator().GeneratorBillSn(BillType.OutStock, BillSource.Process, LoginForm.StoreId);
            }
            InStocks.Orders = OutStocks.Orders;
            InStocks.OutStocks = OutStocks;

            //货品信息

            IList<InStocksProducts> oplist = new List<InStocksProducts>();

            foreach (OutStocksProducts OutStocksProducts in OutStocks.ProductsList) {
                InStocksProducts InStocksProducts = new InStocksProducts();
                InStocksProducts.AllocateAddRate = OutStocksProducts.AllocateAddRate;
                InStocksProducts.Amount = OutStocksProducts.Amount;
                InStocksProducts.PlanQuantity = OutStocksProducts.PlanQuantity;
                InStocksProducts.Price = OutStocksProducts.Price;
                InStocksProducts.Product = OutStocksProducts.Product;
                InStocksProducts.RealInQuantity = OutStocksProducts.RealInQuantity;
                InStocksProducts.RealOutQuantity = OutStocksProducts.RealOutQuantity;
                InStocksProducts.TaxRate = OutStocksProducts.TaxRate;
                oplist.Add(InStocksProducts);
            }
            InStocks.InStocksProductsList = oplist;
            return InStocks;
        }

        private Pickings getPickings() {
            Pickings Pickings = new Pickings();
            Pickings.PickingSn = new BillSNGenerator().GeneratorBillSn(BillType.Order, BillSource.DistributionCenter, LoginForm.StoreId);
            Pickings.OutStocks = OutStocks;
            Pickings.Account = LoginForm.Account;
            Pickings.CreateTime = DateTime.Now;
            Pickings.Salesman = "";
            Pickings.OutWarehouse = OutStocks.OutWarehouse;
            Pickings.InWarehouse = OutStocks.InWarehouse;
            Pickings.OutBillType = "2";
            Pickings.Remark = "系统自动生成";
            IList<PickingsProducts> oplist = new List<PickingsProducts>();
            foreach (OutStocksProducts OutStocksProducts in OutStocks.ProductsList)
            {
                PickingsProducts PickingsProducts = new PickingsProducts();
                //货品id
                PickingsProducts.Product = OutStocksProducts.Product;
                PickingsProducts.Quantity = OutStocksProducts.PlanQuantity;
                PickingsProducts.RealQuantity = OutStocksProducts.RealOutQuantity;
                oplist.Add(PickingsProducts);
            }
            Pickings.PickingsProductsList = oplist;
            return Pickings;
        }

        /// <summary>
        /// 初始化分店下拉框
        /// </summary>
        private void InitStore(){
            StoreBLL StoreBLL = new StoreBLL();
            outStoreCboBox.DataSource =   StoreBLL.FindAll();
         
            OutStoreCboBox1.DataSource = StoreBLL.FindAll();

            InStoreCboBox.DataSource = StoreBLL.FindAll();

            outStoreCboBox.DisplayMember = "StoreName";//显示字段
            outStoreCboBox.ValueMember = "StoreId";//id值
            OutStoreCboBox1.DisplayMember = "StoreName";//显示字段
            OutStoreCboBox1.ValueMember = "StoreId";//id值
            InStoreCboBox.DisplayMember = "StoreName";//显示字段
            InStoreCboBox.ValueMember = "StoreId";//id值
        }
        /// <summary>
        /// 初始化库存地
        /// </summary>
        private void InitWarehouse() {
            if (WarehouseBLL ==null) 
              WarehouseBLL = new WarehouseBLL();
 

            OutWarehouseCbobox2.DataSource = WarehouseBLL.FindByUserAll();
            InWarehouseCbobox.DataSource = WarehouseBLL.FindByUserAll();
            OutWarehouseCbobox1.DataSource = WarehouseBLL.FindByUserAll();

            OutWarehouseCbobox2.DisplayMember = "Name";//显示字段
            OutWarehouseCbobox2.ValueMember = "WarehouseId";//id值

            InWarehouseCbobox.DisplayMember = "Name";//显示字段
            InWarehouseCbobox.ValueMember = "WarehouseId";//id值

            OutWarehouseCbobox1.DisplayMember = "Name";//显示字段
            OutWarehouseCbobox1.ValueMember = "WarehouseId";//id值


        }

        /// <summary>
        /// 初始化财务部部门 和管理部
        /// </summary>
        private void InitDepartment() {
            DepartmentBLL DepartmentBLL = new DepartmentBLL();
           IList<Department> DepartmentList = DepartmentBLL.FindAll();

           this.FinDepartmentCboBox.DataSource = DepartmentList;
           this.MgDepartmentCboBox.DataSource = DepartmentList;

           MgDepartmentCboBox.DisplayMember = "DepName";//显示字段
           MgDepartmentCboBox.ValueMember = "DepId";//id值

           FinDepartmentCboBox.DisplayMember = "DepName";//显示字段
           FinDepartmentCboBox.ValueMember = "DepId";//id值
           
        }
        /// <summary>
        /// 加载承担方式
        /// </summary>
        private void InitAccumeModes() {

            AssumeModeBLL AssumeModeBLL = new AssumeModeBLL();
            IList<AssumeMode> AssumeModeList =  AssumeModeBLL.FindAll();
            BearModelCboBox.DataSource = AssumeModeList;

            BearModelCboBox.DisplayMember = "AssumeModeName";//显示字段
            BearModelCboBox.ValueMember = "AssumeModeId";//id值

        }

        private void next_Click(object sender, EventArgs e)
        {
            pageSize += 1;
            LoadDate();
        }

        private void up_Click(object sender, EventArgs e)
        {
            pageSize -= 1;
            LoadDate();
        }

        private void ProductsDataGridViewOrders_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

            string parameter = ProductsDataGridViewOrders.Columns[e.ColumnIndex].Name;
            if ("ProductCode".Equals(parameter) || "Barcode".Equals(parameter) || "ProductName".Equals(parameter))
            {
                string value = ProductsDataGridViewOrders.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null ? "" : ProductsDataGridViewOrders.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (!"".Equals(value))
                {
                    if (ProductBLL == null) ProductBLL = new ProductBLL();
                    Product Product = ProductBLL.FindProduct(parameter, value);
                    if (Product == null)
                    {
                        MessageBox.Show("没有对应的货品");
                        ProductsDataGridViewOrders.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    }
                    else
                    {
                        ProductsDataGridViewOrders["ProductId", e.RowIndex].Value = Product.ProductId;
                        ProductsDataGridViewOrders["ProductCode", e.RowIndex].Value = Product.ProductCode;
                        ProductsDataGridViewOrders["Barcode", e.RowIndex].Value = Product.Barcode;
                        ProductsDataGridViewOrders["ProductName", e.RowIndex].Value = Product.ProductName;
                        ProductsDataGridViewOrders["Unit", e.RowIndex].Value = Product.Unit == null ? "" : Product.Unit.UnitName;
                        ProductsDataGridViewOrders["PackSpec", e.RowIndex].Value = Product.ProductSpec;

                        
                        //ProductsDataGridViewOrders["PurPrice", e.RowIndex].Value = Product.PurPrice;//未税进价

                        //ProductsDataGridViewOrders["AllocateAddRate", e.RowIndex].Value = Product.AllocateAddRate * 100 + "%";//配送加价率

                        ProductsDataGridViewOrders["inPurPrice", e.RowIndex].Value =
                             Product.PurPrice * (1 + Product.TaxRate);//含税进价 = 未税进价*(1+税率)
                        ProductsDataGridViewOrders["DefPurPrice", e.RowIndex].Value = Product.DefPurPrice;//默认进价
                        ProductsDataGridViewOrders["TaxRate", e.RowIndex].Value = Product.TaxRate;//税率
                         

                    }
                }


            }
            if ("RealOutQuantity".Equals(parameter) || "InMoney".Equals(parameter) || "RealInQuantity".Equals(parameter) || "PlanQuantity".Equals(parameter) )
            {
                Int32 RealOutQuantity = Utils.ToInt(ProductsDataGridViewOrders["RealOutQuantity", e.RowIndex].Value, 0);
                Int32 RealInQuantity = Utils.ToInt(ProductsDataGridViewOrders["RealInQuantity", e.RowIndex].Value, 0);
                Int32 InMoney = Utils.ToInt(ProductsDataGridViewOrders["InMoney", e.RowIndex].Value, 0);
                if (RealOutQuantity != 0 && InMoney != 0)
                {
                    ProductsDataGridViewOrders["totalInMoney", e.RowIndex].Value = RealOutQuantity * InMoney;
                }
                if (RealOutQuantity != 0)
                {
                        //件数
                        ProductsDataGridViewOrders["RealOutQuantityPack", e.RowIndex].Value = RealOutQuantity;
                }
                if (RealOutQuantity != 0)
                {
                    ProductsDataGridViewOrders["RealInQuantityPack", e.RowIndex].Value = RealInQuantity;
                }
                totalNumber();
            }
            //报损数量
            if ( "RealOutQuantitys".Equals(parameter))
            {
                totalNumber();
            }
        }

        /// <summary>
        /// 统计总算
        /// </summary>
        private void totalNumber() {
            Double totalRealOutQuantity = 0;//实际配出数，报损数量
            Double totalRealOutQuantitys = 0;//实际配出数，报损数量
            //进价金额
            Double totalDefPurPrice = 0;
            //计划配送数量
            Double totalPlanQuantity = 0;
            //实际配入数量
            Double totalRealInQuantity = 0;
            for (int i = 0; i < ProductsDataGridViewOrders.Rows.Count - 1; i++)//如果DataGridView中有空的数据，则提示数据输入不完整并退出添加，不包括标题行
            {
              // PlanQuantity = Utils.ToDouble( this.ProductsDataGridViewOrders\["PlanQuantity",i].Value.ToString() ,0); //计划配出数量
              // RealOutQuantity =//实际配出数量
             //  RealInQuantity = this.ProductsDataGridViewOrders.Rows[i].Cells["RealInQuantity"].Value  ;//实际配人数量
              // DefPurPrice= this.ProductsDataGridViewOrders.Rows[i].Cells["DefPurPrice"].Value;//默认进价
              // RealOutQuantity = this.ProductsDataGridViewOrders.Rows[i].Cells["RealOutQuantitys"].Value;//报损数量

               //计算总数
               totalPlanQuantity += Utils.ToDouble(this.ProductsDataGridViewOrders["PlanQuantity", i].Value, 0);
               totalRealOutQuantity += Utils.ToDouble(this.ProductsDataGridViewOrders["RealOutQuantity", i].Value, 0);
               totalRealOutQuantitys += Utils.ToDouble(this.ProductsDataGridViewOrders["RealOutQuantitys", i].Value, 0);
               totalDefPurPrice += Utils.ToDouble( this.ProductsDataGridViewOrders["DefPurPrice",i].Value ,0);
               totalRealInQuantity +=Utils.ToDouble( this.ProductsDataGridViewOrders["RealInQuantity",i].Value , 0) ;
            }
            //总数计算

            InmoneyLabel.Text = "进价金额: " + totalDefPurPrice * totalRealOutQuantitys;
            batNumLabel.Text = "报损数量: " + totalRealOutQuantitys;
            InsendNumTrueLabel.Text = "实际配人数量: " + totalRealInQuantity;//实际配人总数
            sendNumLabel.Text = "计划配出数量: " + totalPlanQuantity;
            OutsendNumTrueLabel.Text = "实际配出数量: " + totalRealOutQuantity;
        
        }

        private void InStoreCboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Store Store = (Store)this.InStoreCboBox.SelectedItem;//获取当前选项
            if (WarehouseBLL == null) 
              WarehouseBLL = new WarehouseBLL();
            InWarehouseCbobox.DataSource = WarehouseBLL.FindWarehouseByStoreId(Store.StoreId, true);
        }

        private void OutStoreCboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Store Store = (Store)this.OutStoreCboBox1.SelectedItem;//获取当前选项
            if (WarehouseBLL == null)
                WarehouseBLL = new WarehouseBLL();
            OutWarehouseCbobox1.DataSource = WarehouseBLL.FindWarehouseByStoreId(Store.StoreId, true);


        }

        private void outStoreCboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Store Store = (Store)this.outStoreCboBox.SelectedItem;//获取当前选项
            if (WarehouseBLL == null) 
              WarehouseBLL = new WarehouseBLL();
            OutWarehouseCbobox2.DataSource = WarehouseBLL.FindWarehouseByStoreId(Store.StoreId, true);
            
        }


    }
}
